<?php
// +----------------------------------------------------------------------
// | 杭州十禾信息科技有限公司
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015 http://www.shelpe.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: LeePuman <ysyzlsm@163.com>
// +----------------------------------------------------------------------

class AutoDriveHpriceModel extends AutoDriveBaseModel{
    
    /** @var 基于competition关键词过滤时不同策略参数 */
    protected $_wordScoreParams = array(
                                                    /*
                                                    1 => 0.5, // 智能平衡模式
                                                    2 => 0.01, // 引流模式
                                                    3 => 0.99, // 小额投资模式
                                                    */
                                                    'ctr_price_desc' => 0.5, // 智能平衡模式
                                                    'pv_desc' => 0.05,  // 引流模式
                                                    'price_asc' => 0.99, // 小额投资模式
                                                );
    
    /** @var 基于hprice出价时候的不同策略参数 */
    protected $_wordPriceParams = array(
                                                        'ctr_price_desc' => 0.95, // 智能平衡模式
                                                        'pv_desc' => 0.95,  // 引流模式
                                                        'price_asc' => 0.95, // 小额投资模式
                                                    );
                                                    
    
    /** @var 关键词得分 **/
    protected $_wordScore = null;
    
    /** @var 类目基础统计信息 */
    protected $_cateProps = null;
	
    /** @var 关键词在类目下单基础统计信息 */
    protected $_cateWordsStats = null;
    
	public function _initialize(){
		parent::_initialize();
		import("@.Library.Carine");
	}
	
	
	
	/**
	 * 
	 * 重设用户使用的出价模型
	 */
	
	public function setPriceType($type){
	    $this->_priceType = AutoDriveBaseModel::$PRICE_TYPES[ $type ];
	    return $this;
	}
	
	/**
	 * 重构filterWords方法
	 * @see parent::filterWords()
	 * 
	 */
	
	public function filterWords(){
        if(!$this->_cndWords)
            return $this;	    
        $this->filterBySex();
        $this->logDebug('After HpriceModel Sex filter: ' . join(', ', array_keys($this->_cndWords)));
        
        //开始基于competition策略的过滤
        $this->filterByCompetition();
	}
	
	protected function filterByCompetition(){
	    // 如果还没有获取候选词统计数据，现在获取
	    if(!$this->_tbStats) {
	        $this->_tbStats = $this->_getKeywordMdl()->getTbStats(array_keys($this->_cndWords),
	                'pv,avg_price,competition,click,ctr,hprice',
	                date('Y-m-d', time() - 3 * 86400), date('Y-m-d', time() - 86400), true);
	    }
	    // 如果还没有获取类目统计数据，现在获取
	    if(!$this->_cateProps) { 
	        $this->_cateProps =  $this->_getCategoryMdl()->getCatBaseAvg($this->_cateId);
	    }	    
	     
	    // 获取关键词的类目基础统计数据
	    if(!$this->_cateWordsStats) {
	        $this->_cateWordsStats =  $this->_getWordMdl()->getWordCatsBasicAvgProps(array_keys($this->_cndWords), $this->_cateId);
	    }
	    $a = $this->_wordScoreParams[ $this->_priceType ];
	    foreach($this->_cndWords as $word => $weight) {
	        if( !isset(  $this->_tbStats[$word] ) ){
	            unset( $this->_cndWords[$word] );
	            continue;
	        }else{
	            $wordStat = $this->_tbStats[$word];
	            $cateWordStat =  $this->_cateWordsStats[$word];
	            $word_competition_all = floatval( $wordStat['competition'] );
	            $word_competition_cat = floatval( $cateWordStat['competition'] );
	            $cat_competition = floatval( $this->_cateProps['competition'] );
	            if( $word_competition_all == 0 ||  $cat_competition == 0 ){
	                $score = 0;
	            }else{
	                $correlation = floatval( $word_competition_cat / $cat_competition );
	                $temp = floatval( $word_competition_cat / $word_competition_all );
	                $score = $this->getWordScore($correlation, $temp, $a);
	            }
	            
	            $this->logDebug( "============= $word ================= ");
	            $this->logDebug(" $word score : $score ,  $word_competition_cat | $word_competition_all  |  $cat_competition | $a " );
	            $this->logDebug(" $word stats : " . json_encode( $cateWordStat ));
	            $this->logDebug( "============= ==== ================= ");
	             
	            //重新定义每个词的权重 @TODO 是否还要考虑用户输入词增加一些？
	            //使用词跟标题相关性适当放大一下score
	            $sim = $this->getWordSim( $word );
	            $score = $score * $sim;
	            $this->_cndWords[$word] = $score;
	        }
	    }	    
	}
	
	/**
	 * 自动开车初始化出价方法
	 * @see parent::setPrice
	 */
	public function setPrice($maxPrice, $numLeft){
		
		
		//开始出价
		$chosenWords = array();
		foreach($this->_cndWords as $word => $score) {
			$wordStat = $this->_tbStats[$word];
			$hprice = $wordStat['hprice'];
			$priceBase = $this->_wordPriceParams[$this->_priceType];
            $point_ratio = $priceBase * pow( $score , 0.2 );
            $point = $this->getHpriceValueGreatThan($hprice, $point_ratio);
            if(empty($point) ){
                $price = 0;
            }else{
                $price = $point[0];
            }
            
            if($price > 0) {
                $price = $price > $maxPrice ? $maxPrice :
                ($price >= AutoDriveBaseModel::MIN_PRICE ? $price : AutoDriveBaseModel::MIN_PRICE);
                $chosenWords[$word] = array(
                        'word' => $word,
                        'max_price' => $price,
                        'matchscope' => AutoDriveBaseModel::DEFAULT_MATCHSCOPE,
                );
                --$numLeft;
            }
            if($numLeft <= 0)
                break;
		}
		
		return $chosenWords;
	}
	
	public function getWordScore( $correlation , $temp , $a ){
	    if( $correlation ==0 || $temp == 0 ) return 0;
		$correlation = $correlation <= 1 ? $correlation : 1;
		$temp = $temp <= 1 ? $temp : 1;
		$temp = pow ( $temp , (0.1 / $temp ) ) ;
		$correlation = pow ( $correlation , (0.1 / $correlation ) );
		$price_score = pow( $temp , (1 - $a) ) * pow ( $correlation  , $a);
		//放大一下score by the similarity with the title
		return $price_score;
	} 

	
	/**
	 * 获取hprice分布中累计分布大于某个值的点
	 * <strong>传入淘宝API返回的hprice字符串结构</strong>
	 * @param $hprice ，淘宝hprice字符串
	 * @param mixed $max，设定的值 ，例如0.3
	 * @return array()， 找到的第一个数组 ，找不到的时候最接近的一个
	 *  
	 */
	
	public function getHpriceValueGreatThan($hprice , $max){
		//先处理hprice
		$hprice = trim( $hprice ,  '{}');
		$hprice = explode(',' , $hprice);
		if( !is_array($hprice) || empty($hprice) ){
			throw new NewzanException('传入hprice参数结构不正确' , RetStatus::PARAM_ERR);
		}
		$hprice = array_chunk( $hprice , 2 );
		$distribution = array();
		$sum = 0;
		usort( $hprice , 'uc_cmp_hprice');
		foreach($hprice as $h){
			$sum += $h[1];
			$distribution[] = array(
					intval($h[0]) , $sum
			);
		}
		foreach( $distribution as &$d){
			$d[1]  = floatval( $d[1]  / $sum );
		}
		
		foreach($distribution as $point){
			if( ! isset( $point[1] ) ) $point[1] = 0;
			if( $point[1] >= $max ){
				return $point;
			}			
		}
		
		return $point;
	}	
	
	/* 标题包含关键词的比率  */
	
	public function getWordSim( $word ){
        try{
        	$carine = new Carine();
	        $resp = $carine->segWords( $word );
	        $respobj = json_decode($resp, true);
	        $seg_words = array_unique( $respobj['response']);
		}catch (Exception $e){
			$seg_words = array($word);
		}
		//calculate similarity 
		$nu = 0;
		$de = count($seg_words);
		foreach( $seg_words as $w){
			if( strpos( $this->_adgroup['title'], $w) )	{
				$nu++;
			}
		}	
		return floatval( $nu / $de );		
	}
	
}
